//
//  ZHWCycleView.m
//  轮播图封装
//
//  Created by dllo on 16/5/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ZHWCycleView.h"
#import "ZHWCycleViewCell.h"
#import "UIImageView+WebCache.h"
#define SECTION_COUNT 1000

@interface ZHWCycleView ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
/** 轮播图控件 */
@property (nonatomic, strong)UICollectionView *collectionView;
/** 数据源数组 */
@property (nonatomic, strong)NSArray *dataSourceArr;
/** 定时器时间间隔 */
@property (nonatomic, assign)CGFloat timeInterval;
/** 定时器对象 */
@property (nonatomic, strong)NSTimer *cycleTimer;
/** 当前item下标  */
@property (nonatomic, assign)NSInteger itemIndex;
/** 当前section下标 */
@property (nonatomic, assign)NSInteger CurrentSection;

@end

@implementation ZHWCycleView

- (instancetype)initWithFrame:(CGRect)frame DataSource:(NSArray *)dataSource TimeInterval:(CGFloat)time
{
    self = [super initWithFrame:frame];
    if (self) {
        // 将外界传递进来的数据源赋值给dataSourceArray
        self.dataSourceArr = dataSource;
        // 初始化布局
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = frame.size;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.scrollDirection = 1;
        
        // 初始化collectionView
        self.collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
        // 滚动条
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        
        [self addSubview:_collectionView];
        
        [self.collectionView registerClass:[ZHWCycleViewCell class] forCellWithReuseIdentifier:@"ZHW_Cell"];
        
        // 设置初始偏移量
        if (self.dataSourceArr.count > 1) {
            
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        }
        
        // 判断间隔时间
        if (time > 0) {
            self.timeInterval = time;
            [self addTimer];
        }
    }
    return self;
}

#pragma mark - item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

#pragma mark - section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return SECTION_COUNT;
}

#pragma mark - item赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataSourceArr.count != 0) {
    ZHWCycleViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZHW_Cell" forIndexPath:indexPath];
    // 记录当前的item和section
        if (indexPath.item > _itemIndex){
            _itemIndex = indexPath.item;
        }
        _CurrentSection = indexPath.section;
   
    if (self.dataSourceArr.count != 0) {
//        cell.cycleImageView.image = self.dataSourceArr[indexPath.item];
        // 网络图片
        [cell.cycleImageView sd_setImageWithURL:[NSURL URLWithString:self.dataSourceArr[indexPath.item]] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    }
    // 添加循环保护
    if (_CurrentSection == SECTION_COUNT - 1) {
        
        [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
    return cell;
    }
    return [UICollectionViewCell new];
}

#pragma mark - 点击item触发的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 代理人实现协议方法
    if (self.delegate != nil) {
        
        [self.delegate didClickedItemAtIndexPath:indexPath];
    }
}

#pragma mark - 添加定时器:
- (void)addTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(changePageByTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.cycleTimer = timer;
}

#pragma mark - 定时器调用的方法
- (void)changePageByTime
{
    if (_itemIndex == self.dataSourceArr.count) {
        _itemIndex = 0;
        _CurrentSection++;
    }
    // 偏移到最新位置(下一张)
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemIndex inSection:_CurrentSection] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    _itemIndex++;
}

#pragma mark - 移除定时器
- (void)removeTimer
{
    [self.cycleTimer invalidate];
    self.cycleTimer = nil;
}

#pragma mark - 手指开始滑动时定时器失效
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}

#pragma mark - 	刷新
- (void)reloadDataByArray:(NSMutableArray *)dataSource
{
    self.dataSourceArr = dataSource;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

@end
